package net.dgg.iboss.sc.backservice.task.service;


import net.dgg.iboss.base.common.exception.BizException;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.MapUtils;
import net.dgg.iboss.base.util.StringUtils;
import net.dgg.iboss.base.util.http.HttpUtility;
import net.dgg.iboss.base.util.http.ResultObj;
import net.dgg.iboss.sc.backservice.task.dao.ProductOrderDao;
import net.dgg.iboss.sc.backservice.task.entity.Node;
import net.dgg.iboss.sc.backservice.task.entity.ProductOrder;
import net.dgg.iboss.sc.backservice.task.util.CommonExcption;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FlowService {
    @Value("${scCmsUrl}")
    private  String sccmsUrl;

    private  String flowApi="/api/sc_cms/out/service/getProcessConfigByParams.do";
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private ZzInProcessService zzInProcessService;

    /**
     * 通过接口获取公共流程节点
     * @param productIds
     * @return
     */
    @Transactional
    public List<Node> getNodeByscCmsUrl(String productIds, String businessCode, Long businessOrgId){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap = this.findNode(productIds,businessCode,businessOrgId);
        if(resultMap==null){
            throw new CommonExcption("没有获取到流程节点,请先配置");
        }
        List<Map<String, Object>> nodeList = new ArrayList<Map<String, Object>>();
        List <Node> nodeList1=new ArrayList<>();
        nodeList = (List) resultMap.get("nodeDtoList");
        for( int i = 0; i < nodeList.size(); i++ ) {
            Node node = new Node();
            MapUtils.map2Bean(node, (Map<String, Object>) nodeList.get(i));
            nodeList1.add(node);
        }
        return nodeList1;
    }

    /**
     * 获取公共流程配置节点
     * @param productIds
     * @return
     */
    public Map findNode(String productIds,String businessCode,Long businessOrgId) {
        Object reMap = new HashMap();

        try {
            Map params = new HashMap();
            params.put("businessProductId", productIds);
            params.put("businessProductCode", businessCode);
            params.put("businessOrgId", businessOrgId);
            String resultStr = HttpUtility.postRest(this.sccmsUrl + this.flowApi, params);
            ResultObj resultObj = (ResultObj) JsonUtil.json2Obj(resultStr, ResultObj.class);
            if (0 != resultObj.getCode()) {
                throw new BizException(resultObj.getMsg());
            }
            reMap = (Map)JsonUtil.json2Obj(resultObj.getData(), Map.class);
        } catch (Exception var6) {
            var6.printStackTrace();
        }
        return (Map)reMap;
    }

    /**
     * 通过生产订单id获取流程节点
     * @param id
     * @return
     */
    @Transactional
    public List<Node> getNode(Long id){
        List<Node> list = new ArrayList<>();
       ProductOrder productOrder = productOrderDao.selectByPrimaryKey(id);
        Map nodeMap = getCurrentNode(productOrder);
        List<Node> listNew = new ArrayList<>();
       if(StringUtils.isEmpty(productOrder.getFlowContent())){
           try {
               list= this.getNodeByscCmsUrl(productOrder.getProductId().toString(),productOrder.getBusinessTypeCode(),productOrder.getProductOrgId());
           }catch (Exception e){
              e.printStackTrace();
           }
       }else {
           list = this.getNodeByFlowContent(productOrder.getFlowContent());
       }
//       if(list.size()>0){
//           for (Node node : list) {
//               if(!nodeMap.get("name").equals("公示") || !nodeMap.get("name").equals("通告")){
//                   if(!node.getCode().equals(nodeMap.get("code"))){
//                       listNew.add(node);
//                   }
//               }else{
//                   listNew.add(node);
//               }
//           }
//       }
       return list;
    }

    /**
     * 通过订单表里保存的流程数据获取流程节点
     * @param flowContent
     * @return
     */

    public List<Node> getNodeByFlowContent(String flowContent){
        if(StringUtils.isEmpty(flowContent)){
            return null;
        }
        Map reMap = new HashMap();
        ResultObj resultObj = (ResultObj) JsonUtil.json2Obj(flowContent, ResultObj.class);
        reMap = (Map)JsonUtil.json2Obj(resultObj.getData(), Map.class);
        List<Map<String, Object>> nodeList = new ArrayList<Map<String, Object>>();
        List <Node> nodeList1=new ArrayList<>();
        nodeList = (List) reMap.get("nodeDtoList");
        for( int i = 0; i < nodeList.size(); i++ ) {
            Node node = new Node();
            MapUtils.map2Bean(node, (Map<String, Object>) nodeList.get(i));
            nodeList1.add(node);
        }
        return nodeList1;
    }

    /**
     * 获取当前节点
     * @param productOrder
     * @return
     */
    public Map getCurrentNode(ProductOrder productOrder){
        Map nodeMap = new HashMap();
        nodeMap.put("id",productOrder.getCurrentNodeId());
        nodeMap.put("name",productOrder.getCurrentNodeName());
        return nodeMap;
    }

    /**
     * 获取公共流程节点信息的字符串
     * @param productIds
     * @param businessCode
     * @return
     */
    public String getFlowNodeStr(String productIds,String businessCode,Long businessOrgId){
        String resultStr="";
        try {
            Map params = new HashMap();
            params.put("businessProductId", productIds);
            params.put("businessProductCode", businessCode);
            params.put("businessOrgId", businessOrgId);
            resultStr = HttpUtility.postRest(this.sccmsUrl + this.flowApi, params);
            ResultObj resultObj = (ResultObj) JsonUtil.json2Obj(resultStr, ResultObj.class);
            if (0 != resultObj.getCode()) {
                throw new BizException(resultObj.getMsg());
            }
            if(null == resultObj.getData()){
                return "";
            }
        } catch (Exception var6) {
            var6.printStackTrace();
            resultStr="";
        }
        return resultStr;
    }

    /**
     * 根据nodeId,生产id 获取 节点信息
     * @param nodeId
     * @param id
     * @return
     */
    public Node queyNodeListById(String nodeId,Long id){
        List<Node> list = this.getNode(id);
        Node returnNode = new Node();
        if(list.size()>0){
            for (Node node : list) {
                if(nodeId.equals(node.getId().toString())){
                    returnNode = node;
                    break;
                }
            }
        }
        return returnNode;
    }
    /**
     * 根据nodeId,生产id 获取 节点信息
     * @param nodeName
     * @param id
     * @return
     */
    public Node queyNodeListByName(String nodeName,Long id){
        List<Node> list = this.getNode(id);
        Node returnNode = new Node();
        if(list.size()>0){
            for (Node node : list) {
                if(nodeName.equals(node.getName())){
                    returnNode = node;
                    break;
                }
            }
        }
        return returnNode;
    }

    /**
     * 根据当前node 获取下一个关键节点
     * @param nodeId
     * @param id
     * @return
     */
    public Node getNextMustNode(String nodeId,Long id){
        if(StringUtils.isEmpty(nodeId) || null == id){
            return null;
        }
        List<Node> list = this.getNode(id);
        Node returnNode = new Node();
        Integer sort = 1000;
        if(list.size()>0){
            for (Node node : list) {
                if(nodeId.equals(node.getId().toString())){
                     sort = node.getSort();
                }
                if(node.getSort()>sort && node.getIsKey()==1){
                    returnNode = node;
                    break;
                }
            }
        }
        return returnNode;
    }

    /**
     * 通过生产订单id获取流程关键节点
     * @param id
     * @return
     */
    public List<Node> getKeyNode(Long id){
        List<Node> list = new ArrayList<>();
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(id);
        Map nodeMap = getCurrentNode(productOrder);
        List<Node> listNew = new ArrayList<>();
        if(StringUtils.isEmpty(productOrder.getFlowContent())){
            list= this.getNodeByscCmsUrl(productOrder.getProductId().toString(),productOrder.getBusinessTypeCode(),productOrder.getProductOrgId());
        }else {
            list = this.getNodeByFlowContent(productOrder.getFlowContent());
        }
        if(list.size()>0){
            for (Node node : list) {
                if(node.getIsKey()==1){
                    listNew.add(node);
                }
            }
        }
        return listNew;
    }

    /**
     * 获取订单当前节点之后的关键节点
     * @param id
     * @return
     */
    public List<Node> getAfterKeyNode(Long id){
        List<Node> list = new ArrayList<>();
        ProductOrder productOrder = productOrderDao.selectByPrimaryKey(id);
        String currentNodeName = productOrder.getCurrentNodeName();
        List<Node> listNew = new ArrayList<>();
        if(StringUtils.isEmpty(productOrder.getFlowContent())){
            list= this.getNodeByscCmsUrl(productOrder.getProductId().toString(),productOrder.getBusinessTypeCode(),productOrder.getProductOrgId());
        }else {
            list = this.getNodeByFlowContent(productOrder.getFlowContent());
        }
        if(list.size()>0){
            Integer sort=100;
            for (Node node : list) {
                if(!productOrder.getLatestEndNodeName().equals("完结")) {
                    if (node.getName().equals(currentNodeName)) {
                        sort = node.getSort();
                        listNew.add(node);
                    }
                    if (node.getIsKey() == 1 && node.getSort() > sort) {
                        listNew.add(node);
                    }
                }
            }
        }
        return listNew;
    }

    /**
     * 获取订单流程的周期时间
     * @param order
     * @return
     */
    public Map getOderCycle(ProductOrder order) {
        Map returnMap = new HashMap();
        Map reMap = new HashMap();
        String str = null;
        if (StringUtils.isEmpty(order.getFlowContent())) {
            str = this.getFlowNodeStr(order.getProductId().toString(),order.getBusinessTypeCode(),order.getProductOrgId());
        }else{
            str=order.getFlowContent();
        }
        if(!StringUtils.isEmpty(str)) {
            ResultObj resultObj = (ResultObj) JsonUtil.json2Obj(str, ResultObj.class);
            reMap = (Map) JsonUtil.json2Obj(resultObj.getData(), Map.class);
            returnMap.put("processingCycle",reMap.get("processingCycle"));
            returnMap.put("cycleType",reMap.get("cycleType"));
        }
        return returnMap;
    }
    /**
     * 获取当前节点后续关键节点的生产天数
     * @param id
     * @return
     */
    public Integer getAfterKyeNodeDays(Long id){
        List<Node> list = new ArrayList<>();
        list = this.getAfterKeyNode(id);
        Integer days = 0;
        if(list.size()>0){
            for(Node node:list){
                days += (int)Math.ceil((double)node.getHandleDate()/24);
            }
        }
        return days;
    }
}
